<template>
  <ele-modal
    :form="true"
    :destroy-on-close="true"
    width="400px"
    v-model="visible"
    title="批量设置学生系别专业">
    <el-form ref="formRef" :model="form" @submit.prevent="" :inline="false" label-position="right">
      <el-form-item label="系别">
        <el-input v-model="form.department" placeholder="请输入学生系别"></el-input>
      </el-form-item>
      <el-form-item label="专业">
        <el-input v-model="form.major" placeholder="请输入学生专业"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>


<script setup>
import {ref, reactive, watch} from 'vue';
import {EleMessage} from 'ele-admin-plus';
import {useFormData} from '@/utils/use-form-data';
import {setDepartmentAndMajor} from "@/api/manage/statistic/admin/studentInfo/index.js";

const props = defineProps({
  /** 修改回显的数据 */
  data: Array
});
const emit = defineEmits(['done']);

/** 弹窗是否打开 */
const visible = defineModel({type: Boolean});

/** 提交状态 */
const loading = ref(false);

/** 表单实例 */
const formRef = ref(null);

/** 表单数据 */
const [form, resetFields, assignFields] = useFormData({
  ids: [],
  department: '',
  major: ''
});

/** 表单验证规则 */
// const rules = reactive({
//   counsellorCode: [
//     {required: true, message: '请选择需要绑定的辅导员', trigger: 'blur'},
//   ]
// });


/** 关闭弹窗 */
const handleCancel = () => {
  visible.value = false;
}


/**
 * 保存
 */
const save = () => {
  formRef.value?.validate?.((valid) => {
    if (!valid) {
      return;
    }
    loading.value = true;
    setDepartmentAndMajor(form).then(res => {
      loading.value = false;
      EleMessage.success({message: res, plain: true});
      handleCancel();
      emit('done');
    }).catch((e) => {
      loading.value = false;
      EleMessage.error({message: e.message, plain: true});
    });
  });
};

/** 监听弹窗打开 */
watch(visible, () => {
  if (visible.value) {
    if (props.data) {
      form.ids = props.data.map(item => item.id);
    }
  } else {
    resetFields();
  }
});

</script>
